<?php

namespace apiend\modules\passport\controllers;

use Yii;
use apiend\components\Controller;
use apiend\modules\passport\models\PasswordForgetForm;
use apiend\modules\passport\models\PasswordResetForm;
use common\helpers\ArrayHelper;

/**
 * 帐号密码找回功能
 * @author emhome <emhome@163.com>
 * @since 2.0
 */
class PasswordController extends Controller {

    /**
     * @inheritdoc
     */
    protected function verbs() {
        return [
            '*' => ['POST'],
        ];
    }

    /**
     * @inheritdoc
     */
    protected function rules() {
        return [
            [
                'actions' => ['forget'],
                'allow' => true,
                'roles' => ['?'],
            ],
            [
                'actions' => ['reset'],
                'allow' => true,
                'roles' => ['@'],
            ],
        ];
    }

    /**
     * 忘记密码
     * @return mixed
     */
    public function actionForget() {
        $model = new PasswordForgetForm();
        $params = Yii::$app->request->post();
        $ms = ArrayHelper::remove($params, 'ms');
        if ($ms) {
            /* @var $security \common\base\Security */
            $security = Yii::$app->security;
            foreach ($params as $k => $v) {
                if ($k == 'code' && strlen($v) == 6) {
                    continue;
                }
                $params[$k] = $security->decryptDataByKey($v);
            }
        }
        if (!$model->load($params, '')) {
            parent::error('请输入要重置的帐号手机号和短信验证码');
        }
        return $model->send();
    }

    /**
     * 修改密码
     * @return mixed
     */
    public function actionReset() {
        $model = new PasswordResetForm();
        $params = Yii::$app->request->post();
        $ms = ArrayHelper::remove($params, 'ms');
        if ($ms) {
            /* @var $security \common\base\Security */
            $security = Yii::$app->security;
            foreach ($params as $k => $v) {
                $params[$k] = $security->decryptDataByKey($v);
            }
        }
        if (!$model->load($params, '')) {
            parent::error('请输入要修改的密码信息');
        }
        $model->user_id = $this->uid;
        return $model->reset();
    }

}
